{
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
}

unit Translator;

interface

uses
  Classes, SysUtils, LResources, LazUTF8, Translations, LCLType, typinfo;

implementation

type
  TTranslator = class(TAbstractTranslator)
  public
    procedure TranslateStringProperty(Sender: TObject; const Instance: TPersistent;
      PropInfo: PPropInfo; var Content: String); override;
  end;

var
  PoFile: TPoFile;

procedure LoadTranslations(const Language: String);
var
  n: Integer;
  ResourceName, s: String;
  Found: Boolean;
  Stream: TResourceStream;
begin
  n := 0;
  repeat
    Inc(n);
    ResourceName := Format('languages/%d.%s.po', [n, Language]);
    Found := FindResource(HINSTANCE, PChar(ResourceName), PChar(RT_RCDATA)) <> 0;
    if Found then
    begin
      Stream := TResourceStream.Create(HINSTANCE, ResourceName, RT_RCDATA);
      try
        SetString(s, Stream.Memory, Stream.Size);
      finally
        Stream.Free;
      end;

      PoFile.ReadPOText(s);
    end;
  until not Found;
end;

procedure InstallTranslator;
var
  Language, FallbackLanguage: String;
begin
  {$HINTS OFF}
  LazGetLanguageIDs(Language, FallbackLanguage);
  {$HINTS ON}

  PoFile := TPOFile.Create;
  LoadTranslations(Language);
  if PoFile.Items.Count = 0 then
    LoadTranslations(FallbackLanguage);

  if PoFile.Items.Count > 0 then
  begin
    TranslateResourceStrings(PoFile);
    Assert( LRSTranslator = nil );
    LRSTranslator := TTranslator.Create;
  end;
end;

procedure UninstallTranslator;
begin
  FreeAndNil(LRSTranslator);
  FreeAndNil(PoFile);
end;

{ TTranslator }

procedure TTranslator.TranslateStringProperty(Sender: TObject; const Instance: TPersistent;
  PropInfo: PPropInfo; var Content: String);
var
  Reader: TReader;
  Id: String;
begin
  if SameText(PropInfo.PropType.Name, 'TTRANSLATESTRING') then
  begin
    Assert( Sender is TReader );
    Reader := TReader(Sender);

    Assert(Reader.Driver is TLRSObjectReader);
    Id := UpperCase(TLRSObjectReader(Reader.Driver).GetStackPath);

    Content := PoFile.Translate(Id, Content);
  end;
end;

initialization

  InstallTranslator;

finalization

  UninstallTranslator;

end.

